package com.hbnu.sunjianwei.questionbank.util;

import com.hbnu.sunjianwei.questionbank.entity.ExamPaper;
import com.hbnu.sunjianwei.questionbank.entity.Question;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 文件导出工具类
 */
public class TextExportUtil {

    /**
     * 导出试卷文件
     */
    public static boolean exportExamPaper(ExamPaper examPaper, String filePath) {
        try {
            // 创建目录
            File directory = new File(filePath).getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 写入试卷文件
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write(generateExamContent(examPaper));
            }

            System.out.println("✅ 试卷文件已导出: " + filePath);
            return true;
        } catch (IOException e) {
            System.err.println("❌ 导出试卷文件失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 导出答案文件
     */
    public static boolean exportAnswerSheet(ExamPaper examPaper, String filePath) {
        try {
            // 创建目录
            File directory = new File(filePath).getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 写入答案文件
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write(generateAnswerContent(examPaper));
            }

            System.out.println("✅ 答案文件已导出: " + filePath);
            return true;
        } catch (IOException e) {
            System.err.println("❌ 导出答案文件失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 生成试卷内容
     */
    private static String generateExamContent(ExamPaper examPaper) {
        StringBuilder content = new StringBuilder();

        // 试卷标题
        content.append("=").append(repeat("=", 50)).append("=\n");
        content.append("                  ").append(examPaper.getTitle()).append("\n");
        content.append("=").append(repeat("=", 50)).append("=\n\n");

        // 试卷信息
        content.append("生成时间: ").append(examPaper.getCreateTime()).append("\n");
        content.append("题目数量: ").append(examPaper.getQuestions().size()).append("题\n\n");

        // 题目列表
        List<Question> questions = examPaper.getQuestions();
        for (int i = 0; i < questions.size(); i++) {
            Question q = questions.get(i);

            content.append(i + 1).append(". ").append(q.getQuestionText()).append("\n");

            // 显示选项
            if ("TRUE_FALSE".equals(q.getQuestionType())) {
                content.append("   A. 正确\n");
                content.append("   B. 错误\n");
            } else {
                if (q.getOptionA() != null && !q.getOptionA().isEmpty())
                    content.append("   A. ").append(q.getOptionA()).append("\n");
                if (q.getOptionB() != null && !q.getOptionB().isEmpty())
                    content.append("   B. ").append(q.getOptionB()).append("\n");
                if (q.getOptionC() != null && !q.getOptionC().isEmpty())
                    content.append("   C. ").append(q.getOptionC()).append("\n");
                if (q.getOptionD() != null && !q.getOptionD().isEmpty())
                    content.append("   D. ").append(q.getOptionD()).append("\n");
            }

            content.append("\n");
        }

        return content.toString();
    }

    /**
     * 生成答案内容
     */
    private static String generateAnswerContent(ExamPaper examPaper) {
        StringBuilder content = new StringBuilder();

        // 答案标题
        content.append("=").append(repeat("=", 50)).append("=\n");
        content.append("                  ").append(examPaper.getTitle()).append(" - 参考答案\n");
        content.append("=").append(repeat("=", 50)).append("=\n\n");

        // 答案信息
        content.append("生成时间: ").append(examPaper.getCreateTime()).append("\n");
        content.append("题目数量: ").append(examPaper.getQuestions().size()).append("题\n\n");

        // 答案列表
        List<Question> questions = examPaper.getQuestions();
        for (int i = 0; i < questions.size(); i++) {
            Question q = questions.get(i);

            content.append(i + 1).append(". ").append(q.getQuestionText()).append("\n");
            content.append("   正确答案: ").append(formatCorrectAnswer(q)).append("\n\n");
        }

        return content.toString();
    }

    /**
     * 格式化正确答案显示
     */
    private static String formatCorrectAnswer(Question question) {
        String answer = question.getCorrectAnswer();
        if ("TRUE_FALSE".equals(question.getQuestionType())) {
            return "A".equals(answer) ? "正确" : "错误";
        }
        return answer;
    }

    /**
     * 生成文件名（包含时间戳）
     */
    public static String generateFileName(String prefix) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
        String timestamp = LocalDateTime.now().format(formatter);
        return prefix + "_" + timestamp + ".txt";
    }

    private static String repeat(String str, int times) {
        StringBuilder sb = new StringBuilder(times * str.length());
        for (int i = 0; i < times; i++) {
            sb.append(str);
        }
        return sb.toString();
    }

}
